<template>
  <q-card
    class="full-height full-width"
    :class="ui.cardClass"
    style="border-radius: 0"
  >
    <q-form @submit="send" style="padding: 20px">
      <br />
      <q-select
        :label="$t(lang + '目标指令')"
        outlined
        v-model="cmd"
        option-label="name"
        :dark="ui.isDark"
        behavior="menu"
        :options="cmdList"
        map-options
        :rules="[(val) => val || $t(lang + '不得为空')]"
      />
      <q-select
        outlined
        :dark="ui.isDark"
        v-model="activePoint"
        :use-input="!point"
        clearable
        :label="$t(lang + '选择导航点')"
        :options="pointList"
        behavior="menu"
        map-options
        option-label="name"
        :rules="[(val) => val]"
      >
        <template v-slot:option="scope">
          <q-item v-bind="scope.itemProps">
            <q-item-section avatar>
              <q-icon
                :name="
                  scope.opt.type === 'charger'
                    ? 'flash_on'
                    : scope.opt.type === 'storage-catch'
                    ? 'precision_manufacturing'
                    : 'room'
                "
              />
            </q-item-section>
            <q-item-section>
              <q-item-label>{{ scope.opt.name }}</q-item-label>
            </q-item-section>
          </q-item>
        </template>
      </q-select>
      <q-select
        :label="$t(lang + '规格')"
        outlined
        v-model="cargo"
        v-if="cmd && cmd.type === 'catch'"
        clearable
        :dark="ui.isDark"
        behavior="menu"
        :options="cargoList"
        :rules="[(val) => (val && val.length > 0) || $t(lang + '不得为空')]"
      />
      <q-btn
        no-caps
        class="full-width text-subtitle1"
        color="primary"
        stretch
        :label="$t(lang + '下发指令')"
        icon="send"
        type="submit"
      >
      </q-btn>
      <q-btn
        no-caps
        class="full-width text-subtitle1 q-mt-sm"
        stretch
        :label="$t(lang + '清空队列')"
        icon="clear"
        color="negative"
        type="button"
        @click="clear"
      >
      </q-btn>
    </q-form>
    <div>
      <q-btn icon="qr_code_scanner" flat @click="visible = true" />
    </div>
    <q-dialog v-model="visible">
      <q-card style="min-width: 15rem" :class="ui.cardClass">
        <q-card-section class="q-px-md text-h6"> 地码实时数据 </q-card-section>
        <q-separator :dark="ui.isDark" />
        <q-card-section class="q-ma-sm">
          <q-item-label class="text-subtitle1"
            >{{ $t("StationCalibrate.位置信息") }}：</q-item-label
          >
          <div class="row q-gutter-x-sm q-mt-sm">
            <q-input
              :dark="ui.isDark"
              dense
              outlined
              type="tel"
              v-model.number="posture.x"
              class="col"
              label="X"
            />
            <q-input
              :dark="ui.isDark"
              dense
              outlined
              type="tel"
              v-model.number="posture.y"
              class="col"
              label="Y"
            />
            <q-input
              :dark="ui.isDark"
              dense
              outlined
              type="tel"
              v-model.number="posture.z"
              class="col"
              label="Z"
            />
          </div>
          <q-item-label class="text-subtitle1 q-mt-sm"
            >{{ $t("StationCalibrate.角度信息") }}：</q-item-label
          >
          <div class="row q-gutter-x-sm q-mt-sm">
            <q-input
              :dark="ui.isDark"
              dense
              outlined
              type="tel"
              v-model.number="posture.qx"
              class="col"
              label="X"
            />
            <q-input
              :dark="ui.isDark"
              dense
              outlined
              type="tel"
              v-model.number="posture.qy"
              class="col"
              label="Y"
            />
            <q-input
              :dark="ui.isDark"
              dense
              outlined
              type="tel"
              v-model.number="posture.qz"
              class="col"
              label="Z"
            />
            <q-input
              :dark="ui.isDark"
              dense
              outlined
              type="tel"
              v-model.number="posture.qw"
              class="col"
              label="W"
            />
          </div>
        </q-card-section>
        <q-btn
          no-caps
          :label="'确认'"
          :class="ui.btnClass"
          class="full-width"
          @click="visible = false"
        />
      </q-card>
    </q-dialog>
  </q-card>
</template>

<script setup>
import { onMounted, ref, watch } from "vue";
import { api } from "boot/axios";
import { useI18n } from "vue-i18n";
import { useQuasar } from "quasar";
import { useAPIStore } from "stores/api";
import { useUiStore } from "stores/ui";
import { status } from "src/utils/deviceWs";
// import MapPoseInfo from 'components/device/MapPoseInfo.vue'

const t = useI18n().t; // 语言包
const lang = "devicePage.DeviceOperate."; // 获取语言是的简写，当前路由名加上 当前文件名
const $q = useQuasar();
const props = defineProps({
  // 地图Id
  mapId: { type: String, default: "" },
  point: {
    type: Object,
    default: () => {},
  },
});

const ui = useUiStore();
const pointList = ref([]); // 点位数据集合
const pointOldList = ref([]); // 旧点位数据集合
const moveCmd = ref({
  // 指令实体
  type: "",
  content: "",
});

const cmd = ref();
const activePoint = ref();
const visible = ref(false);
const posture = ref({});
const cmdList = [
  {
    name: t(lang + "普通移动"),
    type: "move",
    value: "move-basic",
  },
  {
    name: t(lang + "直线行驶"),
    type: "move",
    value: "move-straight",
  },
  {
    name: t(lang + "带方向移动"),
    type: "move",
    value: "move-directional",
  },
  // {
  //   name: t(lang + "抓取"),
  //   type: "catch",
  //   value: "unload",
  // },
  {
    name: t(lang + "取货"),
    type: "catch",
    value: "load",
  },
  {
    name: t(lang + "卸货"),
    type: "catch",
    value: "unload",
  },
  {
    name: t(lang + "自动充电"),
    type: "charge",
    value: "charge",
  },
  {
    name: t(lang + "退出充电"),
    type: "charge",
    value: "uncharge",
  },
];

const cargo = ref("");
const cargoList = ref([]);

// const route = ref([])
// let timer

onMounted(() => {
  getPoint();
});

watch(
  () => props.mapId,
  () => {
    getPoint();
  }
);

watch(
  () => props.point,
  () => {
    if (cmd.value.type.includes("charger")) {
      cmd.value = cmdList[4];
    } else {
      cmd.value = cmdList[1];
    }
    activePoint.value = props.point;
  }
);

watch(cmd, () => {
  if (cmd.value && cmd.value.type.includes("move")) {
    pointList.value = pointOldList.value;
  } else {
    activePoint.value = "";
    pointList.value = pointOldList.value.filter(
      (v) => v.type && v.type.includes(cmd.value.type)
    );
  }
});

let timer;
watch(visible, (value) => {
  if (value) {
    timer = setInterval(getStation, 1000);
  } else {
    clearInterval(timer);
  }
});

// 获取机器人身上当前的数据
function getStation() {
  api
    .post(useAPIStore().amrUrl + "ros/call", [], {
      params: { service: "/dm_code_calibration_pose" },
    })
    .then((rs) => {
      const pose = JSON.parse(rs.data.values.message);
      posture.value.qw = pose.qw.toFixed(6);
      posture.value.qx = pose.qx.toFixed(6);
      posture.value.qy = pose.qy.toFixed(6);
      posture.value.qz = pose.qz.toFixed(6);
      posture.value.x = pose.x.toFixed(6);
      posture.value.y = pose.y.toFixed(6);
      posture.value.z = pose.z.toFixed(6);
    })
    .catch(() => {
      $q.notify({
        type: "negative",
        message: "获取信息失败",
      });
      clearInterval(timer);
    });
}

// 获取点位列表
function getPoint() {
  if (!props.mapId) return;
  // 根据地图id获取点位信息
  api
    .get(useAPIStore().amrUrl + "map/pose/mapID/" + props.mapId)
    .then((res) => {
      pointOldList.value = res.data;
      pointList.value = pointOldList.value;
      cargoList.value = [
        ...new Set(
          status.value.data.cargoList
            .filter((item) => item.type)
            .map((item) => item.type)
        ),
      ];
    });
}

// 获取当前机器人的运动队列
// function getProcessing () {
//   // 获取当前任务的子任务路线
//   api.get(useAPIStore().amrUrl + 'navigation/route').then(rs => {
//     route.value = rs.data
//   })
// }

// 结束当前任务
// function abort () {
//   $q.dialog({
//     title: t(lang + '结束任务'),
//     message: t(lang + '是否要结束任务'),
//     ok: t('ok'),
//     cancel: t('cancel'),
//     dark: ui.isDark,
//     persistent: true
//   }).onOk(() => {
//     api.get(useAPIStore().amrUrl + 'amr/clear').catch(() => {
//       $q.notify({
//         message: t('requestTimeout'),
//         type: 'negative'
//       })
//     })
//   })
// }

// 暂停和继续
// function pause (state) {
//   $q.dialog({
//     title: state ? t(lang + '继续任务') : t(lang + '暂停任务'),
//     message: state ? t(lang + '是否要继续任务') : t(lang + '是否要暂停任务'),
//     ok: t('ok'),
//     cancel: t('cancel'),
//     persistent: true,
//     dark: ui.isDark
//   }).onOk(() => {
//     if (state) {
//       api.get(useAPIStore().amrUrl + 'amr/resume').catch(() => {
//         $q.notify({
//           message: t('requestTimeout'),
//           type: 'negative'
//         })
//       })
//     } else {
//       api.get(useAPIStore().amrUrl + 'amr/pause').catch(() => {
//         $q.notify({
//           message: t('requestTimeout'),
//           type: 'negative'
//         })
//       })
//     }
//   })
// }

// 下发指令
function send() {
  switch (cmd.value.type) {
    case "move":
      moveCmd.value.type = cmd.value.value;
      moveCmd.value.content = activePoint.value.id;
      api
        .post(useAPIStore().amrUrl + "amr/add", moveCmd.value)
        .then((rs) => {
          if (rs.data === "done") {
            $q.notify({
              type: "positive",
              message: t(lang + "指令下发成功"),
            });
          } else {
            $q.notify({ type: "negative", message: "指令下发失败" });
          }
        })
        .catch(() => {
          $q.notify({ type: "negative", message: "接口调用异常" });
        });
      break;
    case "charge":
      api
        .get(useAPIStore().amrUrl + "navigation", {
          params: {
            type: cmd.value.value,
            poseID: activePoint.value.id,
          },
        })
        .then((rs) => {
          if (rs.data) {
            $q.notify({ type: "positive", message: t(lang + "指令下发成功") });
          } else {
            $q.notify({ type: "negative", message: t(lang + "指令下发失败") });
          }
        })
        .catch(() => {
          $q.notify({ type: "negative", message: "接口调用异常" });
        });
      break;
    case "catch": {
      const params = {
        type: cmd.value.value === 'load' ? "load":'unload',
        content: {
          specs: cargo.value,
          count: 1,
          posture: "1-1-1",
          poseID: activePoint.value.id,
        },
      };
      api
        .post(useAPIStore().amrUrl + "amr/add", params)
        .then((rs) => {
          if (rs.data === "done") {
            $q.notify({
              type: "positive",
              message: t(lang + "指令下发成功"),
            });
          } else {
            $q.notify({ type: "negative", message: "指令下发失败" });
          }
        })
        .catch(() => {
          $q.notify({ type: "negative", message: "接口调用异常" });
        });
      break;
    }
    case "load":
    case "unload":{
      const params = {
        type: "load",
        content: {
          specs: cargo.value,
          count: 1,
          posture: "1-1-1",
          poseID: activePoint.value.id,
        },
      };
      api
        .post(useAPIStore().amrUrl + "amr/add", params)
        .then((rs) => {
          if (rs.data === "done") {
            $q.notify({
              type: "positive",
              message: t(lang + "指令下发成功"),
            });
          } else {
            $q.notify({ type: "negative", message: "指令下发失败" });
          }
        })
        .catch(() => {
          $q.notify({ type: "negative", message: "接口调用异常" });
        });
      break;
    }
  }
}

// 清空队列
function clear() {
  api
    .get(useAPIStore().amrUrl + "amr/clear")
    .then((rs) => {
      if (rs.data === "done")
        $q.notify({ type: "positive", message: t(lang + "已清空队列") });
    })
    .catch(() => {
      $q.notify({ type: "negative", message: "接口调用异常" });
    });
}
</script>
